#!/usr/bin/python
# -*- coding: UTF-8 -*-

import requests
import json
import time
import sys

# https://funddb.cn/site/fund_details?fund_code=000090

class FundDB(object):
    def __init__(self):
        print("init")

    def __getRawRealTimeValuation(self, code):
        url = "https://api.jiucaishuo.com/v2/fund-lists/ssjz"
        postHeaders = {
            "accept": "*/*",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "access-control-request-headers": "content-type",
            "access-control-request-method": "POST",
            "cache-control": "no-cache",
            "origin": "https://app.jiucaishuo.com",
            "pragma": "no-cache",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            # "user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Mobile Safari/537.36 Edg/96.0.1054.62"
        }
        headers = {
            # ":authority": "api.jiucaishuo.com",
            # ":method": "POST",
            # ":path": "/v2/fund-lists/ssjz",
            # ":scheme": "https",
            "accept": "application/json, text/plain, */*",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "zh-CN,zh-TW;q=0.9,zh;q=0.8,en;q=0.7",
            # "content-length": "645",
            "content-type": "application/json;charset=UTF-8",
            "origin": "https://funddb.cn",
            # "sec-ch-ua": "\"Chromium\";v=\"94\", \"Yandex\";v=\"21\", \";Not A Brand\";v=\"99\"",
            # "sec-ch-ua-mobile": "?0",
            # "sec-ch-ua-platform": "\"Windows\"",
            # "sec-fetch-dest": "empty",
            # "sec-fetch-mode": "cors",
            # "sec-fetch-site": "cross-site",
            # "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.85 YaBrowser/21.11.4.727 Yowser/2.5 Safari/537.36"
        }

        payloadData = {
            "code":code,
            "type":"h5",
            "version":"1.8.9",
            "ss":"",
            "act_time":(int)(time.time() * 1000),
            "tirgkjfs":""
            ,"abiokytke":"",
            "u54rg5d":"",
            "kf54ge7":"",
            "tiklsktr4":"",
            "lksytkjh":"",
            "sbnoywr":"",
            "bgd7h8tyu54":"",
            "y654b5fs3tr":"",
            "bioduytlw":"",
            "bd4uy742":"",
            "h67456y":"",
            "bvytikwqjk":"",
            "ngd4uy551":"",
            "bgiuytkw":"",
            "nd354uy4752":"",
            "ghtoiutkmlg":"",
            "bd24y6421f":"",
            "tbvdiuytk":"",
            "ibvytiqjek":"",
            "jnhf8u5231":"",
            "fjlkatj":"",
            "hy5641d321t":"",
            "iogojti":"",
            "ngd4yut78":"",
            "nkjhrew":"",
            "yt447e13f":"",
            "n3bf4uj7y7":"",
            "nbf4uj7y432":"",
            "yi854tew":"",
            "h13ey474":"",
            "quikgdky":""
        }
        # payloadData = {
        #     "code":code,
        #     "type":"pc",
        #     "data_source":"xichou",
        #     "version":"1.8.9",
        #     "authtoken":"",
        #     # "act_time":1641385090129,
        #     "act_time":(int)(time.time() * 1000),
        #     "tirgkjfs":"56",
        #     "abiokytke":"e8",
        #     "u54rg5d":"ef",
        #     "kf54ge7":"d",
        #     "tiklsktr4":"6",
        #     "lksytkjh":"a8ae",
        #     "sbnoywr":"ae",
        #     "bgd7h8tyu54":"d9",
        #     "y654b5fs3tr":"8",
        #     "bioduytlw":"c",
        #     "bd4uy742":"a",
        #     "h67456y":"9a8",
        #     "bvytikwqjk":"d9",
        #     "ngd4uy551":"a8",
        #     "bgiuytkw":"fe",
        #     "nd354uy4752":"9",
        #     "ghtoiutkmlg":"8f8",
        #     "bd24y6421f":"e9",
        #     "tbvdiuytk":"9",
        #     "ibvytiqjek":"d3",
        #     "jnhf8u5231":"fe",
        #     "fjlkatj":"ef5",
        #     "hy5641d321t":"9a",
        #     "iogojti":"9",
        #     "ngd4yut78":"f8",
        #     "nkjhrew":"a",
        #     "yt447e13f":"d",
        #     "n3bf4uj7y7":"8",
        #     "nbf4uj7y432":"e8",
        #     "yi854tew":"b9",
        #     "h13ey474":"b9d",
        #     "quikgdky":"71"
        # }

        try:
            opr = requests.post(url, headers=postHeaders)
            opr.encoding = "utf-8"
            # print(opr)
            # print("================================")
            r = requests.post(url, data=json.dumps(payloadData), headers=headers)
            # print(r)
            r.encoding = "utf-8"
            # print(r.text)
            # return r.text
            r_json = json.loads(r.text)
            return r.text
        except Exception as e:
            print(e)
            return None

    def __getRealTimeValuation(self, code):
        loopNum = 10
        while True:
            rdata = self.__getRawRealTimeValuation(code)
            if rdata == None:
                time.sleep(0.05)
            else:
                break
            if loopNum > 0:
                loopNum-=1
            else:
                break
                return ""

        try:
            r_json = json.loads(rdata)
            for d in r_json:
                if d == 'data':
                    rr_json = r_json[d]
                    # print(rr_json)
                    for dd in rr_json:
                        if dd == "series":
                            rrr_json = rr_json[dd][0]
                            # print(rrr_json)
                            for ddd in rrr_json:
                                if ddd == "data":
                                    rrrr_json = rrr_json[ddd]
                                    # print(rrrr_json)
                                    # return rrrr_json
                                    valuation_str = json.dumps(rrrr_json)
                                    # print(type(valuation_str))
#                                    with open("rslt.txt", "w+") as f:
#                                        f.write(valuation_str)
                                    return valuation_str
            return ""
        except Exception as e:
            print(e)
            return ""


    def getRealTimeValuation(self, code):
        raw_str = self.__getRealTimeValuation(code)

#        try:
#            with open("rslt.txt", "r") as f:
#                raw_str = f.read()
#        except Exception as e:
#            return str(e)
#        # print(raw_str)

        if raw_str == "":
            return ""

        raw_json = json.loads(raw_str)

        rslt_list = []
        try:
            for d in raw_json:
                temp_str = [int(d[0]), float(d[1]), float(d[2])]
                rslt_list.append(temp_str)
            # print(rslt_list)
            rslt_json = json.dumps(rslt_list)
#            print(type(rslt_json))
            return rslt_json

        except Exception as e:
            print(e)
            return ""

def getValuation(code):
    fundDB = FundDB()
    return fundDB.getRealTimeValuation(code)

if __name__ == '__main__':    
    print("Testing this module...")
    if len(sys.argv) == 2:
        print(getValuation(sys.argv[1]))
        # fundDB = FundDB()
        # print(fundDB.getRealTimeValuation(sys.argv[1]))
    
    # print())
